<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="10">
          <!-- 搜索栏 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="8">
          <!-- 添加用户按钮 -->
          <el-button type="primary" @click="addDialogVisible = true">
            添加用户
          </el-button>
        </el-col>
      </el-row>
      <!-- 用户数据表格 -->
      <el-table :data="userList" style="width: 100%" :stripe="true" :border="true">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="handleSwitchChange(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <!-- 编辑按钮 -->
          <template slot-scope="scope">
            <el-button type="primary" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" @click="deleteUser(scope.row)">删除</el-button>
            <el-button type="warning" @click="setRole(scope.row)">分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加用户会话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="30%" @close="closeAddDialog">
        <!-- 添加用户输入表单 -->
        <el-form :model="form" :rules="rules" label-width="70px" ref="formRef">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="form.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="30%" @close="closeEditDialog">
        <el-form :model="editUserForm" :rules="rules" label-width="70px" ref="editFormRef">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserForm.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色对话框 -->
      <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="30%" @close="closeSetRoleDialog">
        <div>
          <p>当前用户：{{ userInfo.username }}</p>
          <p>当前角色：{{ userInfo.role_name }}</p>
          <p>
            分配新角色：
            <el-select v-model="selectRoleId" placeholder="请选择">
              <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="changeRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  username: 'Users',
  data() {
    // 邮箱的校验规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-z0-9_-])+@([a-zA-z0-9_-])+(\.[a-zA-z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 号码的校验规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        cb()
      }
      cb(new Error('请输入合法的号码'))
    }
    return {
      // 是否显示对话框
      addDialogVisible: false,
      editDialogVisible: false,
      setRoleDialogVisible: false,
      // 获取用户数据请求参数
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前每页显示数量
        pagesize: 2
      },
      // 获取的用户信息和总数
      userList: [],
      roleList: [],
      selectRoleId: '',
      total: 0,
      // 获取的编辑用户信息
      editUserForm: {},
      userInfo: {},
      // 添加用户表单信息
      form: {
        username: 'admin12',
        password: '123456',
        email: 'admin1@qq.com',
        mobile: '18358585313'
      },
      // 添加用户表单校验
      rules: {
        username: [
          { required: true, message: '请输出用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输出用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输出用户名', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输出用户名', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取用户数据，并把数据保存到data中
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 每页显示数量改变函数，显示数量和页码由请求返回参数决定，所以调用获取用户数据函数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 改变当前显示页码函数
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 改变状态的函数
    async handleSwitchChange(state) {
      const { data: res } = await this.$http.put(`users/${state.id}/state/${state.mg_state}`)
      if (res.meta.status !== 200) {
        state.mg_state = !state.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 添加用户取消按钮清空数据
    closeAddDialog() {
      this.$refs.formRef.resetFields()
    },
    closeEditDialog() {
      this.$refs.editFormRef.resetFields()
    },
    closeSetRoleDialog() {
      this.userInfo = {}
      this.selectRoleId = ''
    },
    // 添加用户函数
    addUser() {
      // 预验证
      this.$refs.formRef.validate(async val => {
        // 预验证通过，发送请求添加用户，关闭对话框，请求用户数据以刷新数据表格
        if (val) {
          const { data: res } = await this.$http.post('users', this.form)
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.addDialogVisible = false
          this.getUserList()
        }
      })
    },
    // 编辑用户信息函数
    async showEditDialog(state) {
      // 根据id查询用户信息
      const { data: res } = await this.$http.get(`users/${state.id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editDialogVisible = true
      this.editUserForm = res.data
    },
    // 修改用户信息函数
    editUser() {
      this.$refs.editFormRef.validate(async val => {
        if (val) {
          const { data: res } = await this.$http.put(`users/${this.editUserForm.id}`, {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile
          })
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.editDialogVisible = false
          this.getUserList()
        }
      })
    },
    deleteUser(state) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async res => {
          const { data: response } = await this.$http.delete(`users/${state.id}`)
          if (response.meta.status !== 200) {
            return this.$message.error(response.meta.msg)
          }
          this.$message.success(response.meta.msg)
          this.getUserList()
        })
        .catch(rea => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配角色按钮
    async setRole(userInfo) {
      this.userInfo = userInfo
      // 获取所有角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    // 分配角色确定按钮
    async changeRole() {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectRoleId
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getUserList()
      this.setRoleDialogVisible = false
    }
  },
  created() {
    // 调用获取用户数据函数
    this.getUserList()
  },
  updated() {}
}
</script>

<style lang="less" scoped></style>
